#!/usr/bin/env python
'''
DocIndexer Microsoft Word 2007 docx parser.
'''
from abstract_parser import AbstractParser
from common import EDocIndexer
import zipfile
import xml.dom.minidom

# From my docx2text.py script.
def nodetext(node):
    n = node.firstChild
    result = ''
    while n:
        if n.nodeType == n.TEXT_NODE:
            result += n.data.rstrip()
            if n.parentNode.getAttribute('xml:space') == 'preserve':
                result += ' '
        elif n.nodeType == n.ELEMENT_NODE:
            tag = n.tagName
            if tag not in ('w:instrText',):
                result += nodetext(n)
            if tag == 'w:p':
                result += '\n\n'
            elif tag in ('w:br','w:cr'):
                result += '\n'
            elif tag == 'w:tab':
                result += ' '
        n = n.nextSibling
    return result

def extract_text(filename):
    z = zipfile.ZipFile(filename)
    try:
        doc = z.read('word/document.xml')
    finally:
        z.close()
    dom = xml.dom.minidom.parseString(doc)
    return unicode(nodetext(dom.documentElement))

class Parser(AbstractParser):

    description = 'Microsoft Word 2007 docx parser'
    mime_types = ['application/vnd.openxmlformats-officedocument.wordprocessingml.document']

    def text(self,filename):
        try:
            return extract_text(filename)
        except:
            raise EDocIndexer,'unable to parse document'


if __name__ == '__main__':
    Parser.test()

# vim: ts=4 sw=4:

